<template>
	<uni-popup ref="popupRef" type="bottom" :is-mask-click="false" background-color="#fff" >
		<view class="payment_box">
			<view class="payment_title_box">
				<view class="payment_title">选择支付方式</view>
				<uni-icons type="closeempty" size="20" @tap="close"></uni-icons>
			</view>
			<view class="payment_list">
				<template v-for="item in paymentList" :key="item.id">
					<view v-if="item.id == 3 ? bankSwitch : true" :class="['payment_item', { payment_item_checked: item.id == selectedPayway }]" @tap="onSelectPayway(item)">
						<view class="payment_content">
							<image :src="item.icon" class="payment_icon"></image>
							<view>{{ item.name }}</view>
						</view>
						<view v-show="item.id != selectedPayway" class="payment_check"></view>
						<image v-show="item.id == selectedPayway" src="https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-13.png" class="payment_checked"></image>
					</view>
				</template>
			</view>
			<view class="footer_box">
				<view class="footer_button" @tap="payForOrder">¥{{ orderInfo.payAmount }} 确认支付</view>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
import { ref } from 'vue';
import { useConfigStoreToRefs } from '@/store/useConfigStore'
import { useUserStoreToRefs } from '@/store/useUserStore'
const { access_token } = useUserStoreToRefs()
const { bankSwitch } = useConfigStoreToRefs()
import api from '@/api';
const emit = defineEmits(['confirm', 'cancel', 'fail']);
const selectedPayway = ref(2);
const popupRef = ref();
const openId = ref();
const paymentList = ref([
	{
		id: 2,
		name: '支付宝支付',
		icon: 'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-40.png'
	},
	{
		id: 3,
		name: '微信支付',
		icon: 'https://xjs-oss-prod.oss-cn-shenzhen.aliyuncs.com/xjs-static/icon-39.png'
	}
]);
const orderInfo = ref({});
const onSelectPayway = (data) => {
	selectedPayway.value = data.id;
};

// 该弹窗用于非抖音支付，包括微信、支付宝等
// 使用该弹窗时需要添加条件编译，避免抖音支付调用该弹窗
// 组件全局注册，可以不用import引入

// data 所需参数
// checkOrderType: 订单检验和支付成功后续功能 petsService 宠物服务，具体名称查询 pages/share/aliPayForQR/index.vue 页面的 checkList;线上商城订单：shopping
// payAmount: 订单金额
// payBusinessType: 支付业务类型 1-服务订单支付  2保证金支付
// orderId: 订单id， payBusinessType为2时可不传

// <paymentPopup ref="paymentPopupRef" @confirm='xxx' />

// // #ifndef MP-TOUTIAO
// paymentPopupRef.value.open({
// 	orderId: 1111111111,
// 	payAmount: 999,
// 	payBusinessType: 1,
//  checkOrderType: 'petsService'
// });
// // #endif
const open = async (data) => {
	orderInfo.value = data || {};
	console.log('data', data);
	console.log('orderInfo.value', orderInfo.value);
	if (Number(orderInfo.value.payAmount) == 0) {
		payForOrder();
		return;
	}
	uni.hideLoading()
	popupRef.value.open();
	
	// #ifdef MP-WEIXIN
	await getOpenId();
	// #endif
};
const close = () => {
	popupRef.value.close();
	emit('cancel');
};
const payForOrder = async () => {
	uni.showLoading({
		mask: true
	});
	const payBusinessType = orderInfo.value.payBusinessType || 1;
	// payType 1 抖音， 2 支付宝  3 微信小程序支付
	const payType = selectedPayway.value;
	
	let paymentParams = `/mall/payment/pay/${payBusinessType}/${payType}/?orderId=${orderInfo.value.orderId}`;
	
	// #ifdef APP
	paymentParams += `&tradeType=app`
	// #endif
	
	// #ifdef MP-WEIXIN
	if (payType == 3) {
		paymentParams += `&tradeType=jsapi&openId=${openId.value}`;
	}
	// #endif
	console.log('paymentParams', paymentParams)
	const result = await api({
		method: 'post',
		url: paymentParams
	});
	console.log('result', result)
	if (result.code != 0) {
		uni.hideLoading();
		setTimeout(() => {
			uni.showToast({
				icon: 'none',
				title: '支付失败'
			});
			emit('fail');
		}, 1000);
		return;
	}

	if (Number(orderInfo.value.payAmount) == 0) {
		uni.showToast({
			title: '支付成功'
		});
		uni.hideLoading();
		emit('confirm', {
			orderId: orderInfo.value.orderId
		});
		return;
	}
	switch (Number(payType)) {
		case 2:
			await aliPay(result);
			break;
		case 3:
			await wxPay(result);
			break;
	}

	uni.hideLoading();
};

const aliPay = async (data) => {
	// #ifdef APP
	return await uni.getProvider({
		service: "payment",
		success: (res) => {
			if (~res.provider.indexOf("alipay")) {
				uni.requestPayment({
					provider: "alipay",
					orderInfo: data.data || {},
					success: (result) => {
						uni.showToast({
							title: '支付成功'
						});
						emit('confirm', {
							orderId: orderInfo.value.orderId
						});
					},
					fail: (error) => {
						uni.showToast({
							icon: 'none',
							title: '支付失败'
						});
						emit('fail');
					},
				});
			}
		},
	});
	// #endif
	
	const shortUrl = await api({
		prefix: 'acc',
		method: 'post',
		url: `/shortUrl/generate`,
		header: {
			contentType: 'json'
		},
		data: {
			longUrl: data.data
		}
	});
	uni.redirectTo({
		url: `/pages/share/aliPayForQR/index?orderId=${orderInfo.value.orderId}&checkOrderType=${orderInfo.value.checkOrderType}&payAmount=${
			orderInfo.value.payAmount
		}&url=${encodeURIComponent(shortUrl.data)}`
	});
};

const wxPay = async (data) => {
	console.log('wxPay', data)
	console.log('useUserStoreToRefs',access_token.value)
	console.log('orderInfo.value',orderInfo.value)
	// #ifdef APP
	return await uni.getProvider({
		service: "payment",
		success: (res) => {
			if (~res.provider.indexOf("wxpay")) {
				uni.requestPayment({
					provider: "wxpay",
					orderInfo: data.data || {},
					success: (result) => {
						uni.showToast({
							title: '支付成功'
						});
						emit('confirm', {
							orderId: orderInfo.value.orderId
						});
					},
					fail: (error) => {
						uni.showToast({
							icon: 'none',
							title: '支付失败'
						});
						console.log('error', error)
						emit('fail');
					},
				});
			}
		},
	});
	// #endif
	
	// #ifdef MP-WEIXIN
	const params = data.data;
	return await uni.getProvider({
		service: 'payment',
		success: async (res) => {
			if (~res.provider.includes('wxpay')) {
				await uni.requestPayment({
					provider: 'wxpay',
					timeStamp: params.timeStamp,
					nonceStr: params.nonceStr,
					package: params.package,
					signType: params.signType,
					paySign: params.sign,
					success(res) {
						uni.showToast({
							title: '支付成功'
						});
						emit('confirm', {
							orderId: orderInfo.value.orderId
						});
					},
					fail(e) {
						console.log('微信支付失败', e);
						uni.showToast({
							icon: 'none',
							title: '支付失败'
						});
						emit('fail');
					}
				});
			}
		}
	});
	// #endif
};

const getOpenId = async () => {
	await uni.login({
		success: async (res) => {
			const { data } = await api({
				method: 'GET',
				url: '/mall/wx/xcx/jsapi/token',
				data: { code: res.code }
			});
			openId.value = data.openid;
		}
	});
};

defineExpose({ open,close });
</script>

<style lang="scss" scoped>
.payment_box {
	position: relative;
	background: #ffffff;
	border-radius: 24rpx 24rpx 0rpx 0rpx;
	padding: 68rpx 32rpx;
	height: 75vh;
	box-sizing: border-box;

	.payment_title_box {
		display: flex;
		justify-content: space-between;
		align-items: center;
		font-weight: bold;
		font-size: 40rpx;
		color: #1b2120;
		margin-bottom: 52rpx;
	}
	.payment_list {
		.payment_item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			height: 176rpx;
			border: 2rpx solid #e4e6e6;
			border-radius: 24rpx;
			margin-bottom: 32rpx;
			padding: 0 32rpx;
			box-sizing: border-box;

			.payment_content {
				display: flex;
				align-items: center;
				font-size: 32rpx;
				color: #1b2120;

				.payment_icon {
					width: 48rpx;
					height: 48rpx;
					border-radius: 50%;
					margin-right: 24rpx;
				}
			}

			.payment_check {
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
				border: 2rpx solid #1b2120;
				box-sizing: border-box;
			}
			.payment_checked {
				width: 40rpx;
				height: 40rpx;
				border-radius: 50%;
			}
		}
		.payment_item_checked {
			border: 2rpx solid #ff6084;
		}
	}

	.footer_box {
		width: 100%;
		box-sizing: border-box;
		position: absolute;
		bottom: 0;
		left: 0;
		padding: 6rpx 40rpx;
		border-top: 1rpx solid #e6f6f6;
		// padding-bottom: calc(constant(safe-area-inset-bottom));
		// padding-bottom: calc(env(safe-area-inset-bottom));

		.footer_button {
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 28rpx;
			color: #ffffff;
			background: linear-gradient(90deg, #ff6188 0%, #ff5252 100%);
			border-radius: 62rpx;
		}
	}
}
</style>
